package com.shopping.security;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    // 定义不需要认证的公开路径
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
            "/api/user/register",
            "/api/user/login",
            "/api/comments/product/",  // 只允许查看评论的GET请求
            "/api/images/",
            "/api/upload/",
            "/uploads/",
            "/api/message/list",
            "/api/comments/product/*/rating"  // 允许查看评分
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String requestTokenHeader = request.getHeader("Authorization");
        String username = null;
        String jwtToken = null;

        // 检查请求路径是否需要认证
        String requestPath = request.getRequestURI();
        boolean isPublicPath = PUBLIC_PATHS.stream()
                .anyMatch(path -> {
                    if (path.equals("/api/comments/product/")) {
                        return requestPath.startsWith(path) && request.getMethod().equals("GET");
                    }
                    if (path.equals("/api/comments/product/*/rating")) {
                        return requestPath.matches("/api/comments/product/\\d+/rating");
                    }
                    return requestPath.startsWith(path);
                });

        if (isPublicPath) {
            chain.doFilter(request, response);
            return;
        }

        // 从请求头中获取JWT Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtUtil.extractUsername(jwtToken);
            } catch (IllegalArgumentException e) {
                log.error("无法获取JWT Token");
            } catch (ExpiredJwtException e) {
                log.error("JWT Token已过期");
            }
        } else {
            log.warn("JWT Token不存在或格式不正确");
        }

        // 验证Token
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
                log.info("用户认证成功: username={}", username);
            }
        }

        chain.doFilter(request, response);
    }
}
